
package com.milan.analysis.common.extend;

import com.milan.analysis.common.exception.WsServiceResponseException;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * CommonHandlerExceptionResolver
 *
 * @author liaozhidan
 */
public class CommonHandlerExceptionResolver extends DefaultHandlerExceptionResolver {

    public CommonHandlerExceptionResolver(String s, String s2, String s23, String s234) {
    }

    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = super.doResolveException(request, response, handler, ex);

        try {
            if (modelAndView == null) {
                if (ex instanceof IllegalArgumentException) {
                    modelAndView = handleIllegalArgumentException((IllegalArgumentException) ex, request, response, handler);
                } else {
                    if (ex instanceof WsServiceResponseException) {
                        modelAndView = new ModelAndView("common/error");
                        WsServiceResponseException wsServiceResponseException = (WsServiceResponseException) ex;
                        if (wsServiceResponseException.isBusinessError()) {
                            request.setAttribute("errorCode", wsServiceResponseException.getErrorCode());
                            request.setAttribute("errorMsg", wsServiceResponseException.getMessage());
                        } else {
                            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return modelAndView;
    }

    private ModelAndView handleIllegalArgumentException(IllegalArgumentException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }

        return null;
    }
}
